import numpy as np
import cv2
import tensorflow as tf
#加载本地人脸分类器
face_cascade = cv2.CascadeClassifier('G:\TensorFlow\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
model = tf.keras.models.load_model('test.h5')

cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))

while(True):
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in face:
        face = img[y:y + h, x:x + w]
        face = cv2.resize(face, (64, 64))
        img_predict = np.array(face) / 255.0
        p = model.predict(img_predict[np.newaxis, ...])
        maxindex = np.argmax(p[0])
        if maxindex == 0:
            label = 'gaoliangyu'
        elif maxindex == 1:
            label = 'suyalong'
        elif maxindex == 2:
            label = 'yinwenqiang'
        cv2.putText(img, label , (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    cv2.imshow('frame',img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


cap.release()
cv2.destroyAllWindows()